/**
 * Copyright 2019 吉鼎科技.

 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.easyplatform.engine.runtime.jxls;

import cn.easyplatform.EasyPlatformWithLabelKeyException;
import cn.easyplatform.contexts.ReportContext;
import cn.easyplatform.contexts.WorkflowContext;
import cn.easyplatform.dos.FieldDo;
import cn.easyplatform.engine.runtime.ComponentProcess;
import cn.easyplatform.entities.beans.report.JxlsReport;
import cn.easyplatform.interceptor.CommandContext;
import cn.easyplatform.lang.Strings;
import cn.easyplatform.lang.stream.StringInputStream;
import cn.easyplatform.messages.vos.ReportVo;
import cn.easyplatform.type.FieldType;
import org.apache.commons.io.IOUtils;
import org.jxls.area.Area;
import org.jxls.area.CommandData;
import org.jxls.builder.xml.XmlAreaBuilder;
import org.jxls.command.EachCommand;
import org.jxls.common.Context;
import org.jxls.transform.Transformer;
import org.jxls.transform.poi.PoiTransformer;
import org.jxls.util.JxlsHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author: <a href="mailto:davidchen@epclouds.com">littleDog</a> <br/>
 * @Description:
 * @Since: 2.0.0 <br/>
 * @Date: Created in 2019/10/17 9:55
 * @Modified By:
 */
public class JxlsReportProcess implements ComponentProcess<JxlsReport, ReportVo, byte[]> {

    private final static Logger log = LoggerFactory.getLogger(JxlsReportProcess.class);

    @Override
    public byte[] doComponent(CommandContext cc, ReportVo rv, JxlsReport entity) {
        if (entity.getTemplate() == null)
            throw new EasyPlatformWithLabelKeyException(
                    "report.entity.no.compile", entity.getId());
        WorkflowContext ctx = cc.getWorkflowContext();
        ReportContext report = ctx.setReport(rv.getId(), rv.getEntityId(),
                rv.getIds(), rv.getState(), entity.getTable());
        if (rv.getState() == 'U' || rv.getState() == 'R') {
            StringBuilder sb = new StringBuilder();
            for (String name : rv.getIds().split(","))
                sb.append(ctx.getRecord().getValue(name));
            List<FieldDo> params = new ArrayList<FieldDo>();
            FieldDo fd = new FieldDo(FieldType.VARCHAR);
            fd.setValue(report.getEntityId());
            fd.setName("reportid");
            params.add(fd);
            fd = new FieldDo(FieldType.VARCHAR);
            fd.setValue(sb.toString());
            fd.setName("bizid");
            params.add(fd);
            FieldDo obj = cc
                    .getBizDao()
                    .selectObject(
                            "select content from sys_report_log where reportid=? and bizid=?",
                            params);
            if (obj != null)
                return (byte[]) obj
                        .getValue();
            if (rv.getState() == 'R')// 如果是R类型找不到对应的记录就出错
                throw new EasyPlatformWithLabelKeyException(
                        "report.print.not.found", report.getEntityId(), sb);
        }
        Context context = null;
        if (!Strings.isBlank(rv.getFrom())) {
            context = new FromTaskReportHandler().createContext(cc, rv, rv.getFrom());
        } else
            context = new SimpleJxlsReportHandler().createContext(cc, rv, cc.getWorkflowContext().getRecord());
        InputStream is = null;
        ByteArrayInputStream bis = null;
        ByteArrayOutputStream bos = null;
        Transformer transformer = null;
        try {
            bis = new ByteArrayInputStream(entity.getTemplate());
            bos = new ByteArrayOutputStream();
            JxlsHelper jxlsHelper = JxlsHelper.getInstance();
            transformer = jxlsHelper.createTransformer(bis, bos);
            if (!Strings.isBlank(entity.getConfig()))
                jxlsHelper.setAreaBuilder(new XmlAreaBuilder(is = new StringInputStream(entity.getConfig()), transformer));
            else
                jxlsHelper.getAreaBuilder().setTransformer(transformer);
            List<Area> xlsAreaList = jxlsHelper.getAreaBuilder().build();
            if (xlsAreaList.isEmpty())
                throw new IllegalStateException("No XlsArea were detected for this processing");
            for (Area area : xlsAreaList) {
                if (!Strings.isBlank(area.getEvent()))
                    area.addAreaListener(new JxlsAreaListener(cc, (PoiTransformer) transformer, area.getEvent()));
            }
            Area area = xlsAreaList.get(0);
            boolean multisheet = false;
            //判断是否生成多个表格
            if (!area.getCommandDataList().isEmpty()) {
                CommandData cmd = area.getCommandDataList().get(0);
                if (cmd.getCommand() instanceof EachCommand) {
                    EachCommand each = (EachCommand) cmd.getCommand();
                    multisheet = !Strings.isBlank(each.getMultisheet());
                }
            }
            jxlsHelper.setDeleteTemplateSheet(true).setProcessFormulas(entity.getFormulaType() != 0).setUseFastFormulaProcessor(entity.getFormulaType() == 1);
            if (multisheet) {
                jxlsHelper.processTemplate(context, xlsAreaList);
            } else
                jxlsHelper.processTemplateAtCell(context, xlsAreaList, "Result!A1");

            byte[] data = bos.toByteArray();
            report.setPrint(data);
            return data;
        } catch (Exception ex) {
            if (log.isErrorEnabled())
                log.error("doComponent", ex);
            throw new EasyPlatformWithLabelKeyException("report.fill.error",
                    ex, entity.getId(), ex.getMessage());
        } finally {
            IOUtils.closeQuietly(is);
            IOUtils.closeQuietly(bis);
            IOUtils.closeQuietly(bos);
            if (transformer != null)
                transformer.dispose();
        }
    }

}
